import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def get_user_by_count(account):
    try:
        if re.match(r'1[3-9][0-9]{9}', account):
            # 从mysql数据库中通过手机号码取出这一行数据,赋值给user,相当于给authenticate增加了mobile取值的方法
            user = User.objects.get(mobile=account)

        else:
            user = User.objects.get(username=account)

    except Exception as e:
        return None

    # 无异常是执行else 无论有无异常都会执行finally
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_count(username)

        # 相当于改写了从数据库取数据的方法,自带的方法只能用username取值,我们增加了从手机号码取值
        if user and user.check_password(password):
            return user